package config

import (
	"fmt"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"os"
	"path/filepath"
	"sync"
)


type RedisConfig struct {
	Address     string
	Prefix      string
	PoolSize    int
	PoolTimeOut int
}

type MysqlConfig struct {
	Name       string
	Password   string
	Address    string
	Database   string
	MaxIdle    int
	MaxContent int
}
type LogConfig struct {
	Level         string
	RotationTime  int
	RotationCount int
}

type Config struct {
	Redis  RedisConfig
	Mysql  MysqlConfig
	Log    LogConfig
}

// 初始化config
func (c *Config) initConfig() {
	viper.SetConfigType("yaml")
	viper.SetConfigName("config")
	//viper.AddConfigPath("./config")
	viper.AddConfigPath("/etc")
	homeDir, err := os.UserHomeDir()
	if err == nil {
		viper.AddConfigPath(homeDir)
	}
	abs, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Error(err.Error())
	}
	viper.AddConfigPath(abs + "/config")
	viper.AddConfigPath("./config")

	err = viper.ReadInConfig()
	if err != nil {
		log.Error(fmt.Errorf("Fatal error config file: %s \n", err))
	}
	c.readConfig()
}

// 读取config
func (c *Config) readConfig() {
	// 读取redis配置
	c.Redis.Address = viper.GetString("redis.address")
	c.Redis.Prefix = viper.GetString("redis.prefix")
	c.Redis.PoolSize = viper.GetInt("redis.poolSize")
	c.Redis.PoolTimeOut = viper.GetInt("redis.poolTimeOut")

	// 读取mysql配置
	c.Mysql.Name = viper.GetString("mysql.name")
	c.Mysql.Password = viper.GetString("mysql.password")
	c.Mysql.Address = viper.GetString("mysql.address")
	c.Mysql.Database = viper.GetString("mysql.database")
	c.Mysql.MaxIdle = viper.GetInt("mysql.maxIdle")
	c.Mysql.MaxContent = viper.GetInt("mysql.maxContent")

	// 读取log Level配置
	c.Log.Level = viper.GetString("log.level")
	c.Log.RotationTime = viper.GetInt("log.rotationTime")
	c.Log.RotationCount = viper.GetInt("log.rotationCount")
}

var C *Config
var once sync.Once

// 获取单例
func GetConfigInstance() *Config {
	once.Do(func() {
		C = new(Config)
		C.initConfig()
	})
	return C
}
